package com.hotel.api.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hotel.api.entity.Room;
import com.hotel.api.entity.User;
import com.hotel.api.entity.UserChangeRoom;
import com.hotel.api.service.RoomService;
import com.hotel.api.service.UserService;
import com.hotel.api.utils.JSONResult;
import com.hotel.api.vo.RoomVO1;
import com.hotel.api.vo.UserChangerRoomVO;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.view.groovy.GroovyMarkupConfig;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 宿舍操作Controller
 *
 * @Author 涛涛
 * @Create 2019/8/29
 */

@RestController
@RequestMapping("/room")
public class RoomController {
    @Autowired
    RoomService roomService;

    @Autowired
    UserService userService;

    /*
     插入宿舍
     */
    @ApiOperation("插入宿舍")
    @PostMapping("/insertRoom")
    public JSONResult insertRoom(Room room) {
        if (room.getRoomNumber() == null || room.getType() == null || room.getCompany() == null) {
            return JSONResult.build(500, "请填写完整信息", null);
        }
        Room room1 = roomService.selectRoomByRoomNumber(room.getRoomNumber());
        if (room1 != null) {
            return JSONResult.build(501, "已存在此宿舍", null);
        } else {
            room.setLivedPeopleNumber(0);
            room.setAvailable(room.getType() - room.getLivedPeopleNumber());
            int insert = roomService.insert(room);
            if (insert == 0) {
                return JSONResult.errorException("插入失败");
            } else {
                return JSONResult.build(200, "插入成功", insert);
            }
        }

    }

    /**
     * 管理员查看宿舍情况
     *
     * @param page
     * @param limit
     * @param rid
     * @return
     */

    @ApiOperation("管理员查看宿舍情况")
    @PostMapping("/selectUserRooms")
    public JSONResult selectUserRooms(Integer page, Integer limit, Integer rid) {
        if (rid == null) {
            PageHelper.startPage(page, limit);
            List<Room> list = roomService.selectUserRooms();
            PageInfo<Room> pageInfo = new PageInfo<>(list);
            if (list.size() == 0) {
                return JSONResult.errorMsg("暂无信息");
            } else {
                return JSONResult.build(200, "查询成功", pageInfo);
            }
        } else {
            Room room = roomService.selectRoomByRoomNumber(rid);
            if (room == null) {
                return JSONResult.errorMsg("没有" + rid + "这个房间");
            }
            PageHelper.startPage(page, limit);
            List<Room> list = roomService.selectUserRoomsByRoomNum(rid);
            PageInfo<Room> pageInfo = new PageInfo<>(list);
            return JSONResult.build(200, "查询房间号为" + rid + "的用户成功", pageInfo);
        }
    }

    /**
     * 查看宿舍
     *
     * @param page
     * @param limit
     * @param rid
     * @return
     */
    @ApiOperation("查看宿舍")
    @PostMapping("/selectAllRooms")
    public JSONResult selectAllRoom(Integer page, Integer limit, Integer rid) {
        if (rid == null) {
            PageHelper.startPage(page, limit);
            List<Room> list = roomService.selectAll();
            PageInfo<Room> pageInfo = new PageInfo<>(list);
            if (list.size() == 0) {
                return JSONResult.errorException("无宿舍信息");
            } else {
                return JSONResult.build(200, "查询成功", pageInfo);
            }
        } else {
            ArrayList<Room> rooms = new ArrayList<>();
            Room room = roomService.selectRoomByRoomNumber(rid);
            rooms.add(room);
            if (rooms != null) {
                return JSONResult.build(200, "查询房间号为" + rid + "的用户成功", rooms);
            } else {
                return JSONResult.errorMsg("没有" + rid + "这个房间");
            }
        }
    }

    /**
     * 根据宿舍id更新宿舍信息
     *
     * @param room
     * @return
     */

    @PostMapping("/updateRoomInfoById")
    public JSONResult updateRoomInfoById(Room room) {
        int i = roomService.updateRoomInfoById(room);
        if (i != 0) {
            return JSONResult.ok("更新成功");
        }
        return JSONResult.errorMsg("更新失败");
    }


    /**
     * 根据宿舍类型查找宿舍
     *
     * @param type
     * @return
     */
    @ApiOperation("根据宿舍类型查找宿舍")
    @PostMapping("/selectRoomByTypeRoom/{type}")
    public JSONResult selectRoomByTypeRoom(@PathVariable("type") Integer type) {
        List<Room> list = roomService.selectRoomByTypeRoom(type);
        if (list.size() == 0) {
            return JSONResult.errorException("查询无该宿舍类型");
        } else {
//            JSONResult.build(200, "查询到该宿舍类型", list);
            return JSONResult.build(200, "查询成功", list);
        }
    }

    /*
    根据宿舍号查找该宿舍
     */
    @ApiOperation("根据宿舍号查找该宿舍")
    @PostMapping("/selectNameByRoomNumber")
    public JSONResult selectRoomByRoomNumber(Integer roomNumber) {
        System.out.println("根据宿舍号查找该宿舍");
        List<Room> list = roomService.selectNameByRoomNumber(roomNumber);
        if (list.size() == 0) {
            return JSONResult.errorException("无该宿舍号");
        } else {
            return JSONResult.build(200, "查询到该宿舍号", list);
        }
    }

    /*
    根据宿舍归属公司查找宿舍
     */
    @ApiOperation("根据宿舍归属公司查找宿舍")
    @PostMapping("/selectRoomByCompany/{company}")
    public JSONResult selectRoomByCompany(@PathVariable String company) {
        List<Room> list = roomService.selectRoomByCompany(company);
        if (list.size() == 0) {
            return JSONResult.errorException("无该归属企业宿舍");
        } else {
            return JSONResult.build(200, "查询到该企业宿舍", list);
        }
    }

    /*
    根据宿舍号删除宿舍
     */
    @ApiOperation("根据宿舍号删除宿舍")
    @PostMapping("/deleteRoomByRoomNumber")
    public JSONResult deleteRoomByRoomNumber(Integer rid) {
        int room = roomService.deleteRoomByRoomNumber(rid);
        if (room == 0) {
            return JSONResult.errorException("无该宿舍，删除失败");
        } else {
            return JSONResult.build(200, "删除宿舍成功", room);
        }
    }

    /*
    根据宿舍号更新宿舍类型
     */
    @ApiOperation("根据宿舍号更新宿舍类型")
    @PostMapping("/updateRoomByType")
    public JSONResult updateRoomByType(Room r1) {

        int room = roomService.updateRoomByType(r1);
        if (room == 0) {
            return JSONResult.errorException("查无该宿舍，更新宿舍类型失败");
        } else {
            JSONResult.build(200, "更新宿舍类型成功", room);
            return JSONResult.ok();
        }
    }

    /*
    用户申请退换宿，将用户想申请的类型以及原因插入到数据库中
     */
    @ApiOperation("用户申请退换宿")
    @PostMapping("/UserChangeRoom")
    public JSONResult UserChangeRoom(UserChangeRoom userChangeRoom) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date = df.format(new Date());
        userChangeRoom.setCreateTime(date);
        int i = (int) userChangeRoom.getType();
        String type = i == 1 ? "退宿" : "换宿";
        UserChangeRoom userChangeRoom1 = roomService.selectUserChangeRoomByUserId(userChangeRoom.getUid());
        if (userChangeRoom1 == null) {
            User user = userService.selectById(userChangeRoom.getUid());
            if (userChangeRoom.getChangeRoomId().equals(user.getRoomId()) && userChangeRoom.getType() == 2) {
                return JSONResult.build(401, "更换宿舍跟目前居住宿舍相同", null);
            }
            roomService.userChangeRoom(userChangeRoom);
            return JSONResult.build(200, "申请" + type + "成功", null);
        }
        return JSONResult.build(500, "不能重复提交申请", null);

    }

    @ApiOperation("查看用户退换宿申请")
    @PostMapping("/selectUserChangeRoomOrders")
    public JSONResult selectAlselectUserApplylRoom(@RequestParam(value = "page", defaultValue = "0", required = false) Integer page,
                                                   @RequestParam(value = "limit", defaultValue = "10", required = false) Integer limit) {
        List<UserChangeRoom> list = roomService.selectUserChangeRoomOrders();
        PageHelper.startPage(page, limit);
        PageInfo<UserChangeRoom> pageInfo = new PageInfo<>(list);
        if (list.size() == 0) {
            return JSONResult.errorException("无用户申请换宿");
        } else {
            return JSONResult.build(200, "查询成功", pageInfo);
        }
    }


    /*
    根据宿舍号更新宿舍照片
     */
    @ApiOperation("根据宿舍号更新宿舍照片")
    @PostMapping("/updateRoomByPhoto")
    public JSONResult updateRoomByPhoto(String photo, int roomNumber) {
        int room = roomService.updateRoomByPhoto(photo, roomNumber);
        if (room == 0) {
            return JSONResult.errorException("更换照片失败");
        } else {
            JSONResult.build(200, "更换照片成功", room);
            return JSONResult.ok();
        }
    }

    /*
    根据宿舍号更新归属公司
     */
    @ApiOperation("根据宿舍号更新归属公司")
    @PostMapping("/updateRoomByCompany")
    public JSONResult updateRoomByCompany(int roomNumber, String company) {

        int room = roomService.updateRoomByCompany(company, roomNumber);
        if (room == 0) {
            return JSONResult.errorException("更新归属公司失败");
        } else {
            JSONResult.build(200, "更新归属公司成功", room);
            return JSONResult.ok();
        }
    }


    @ApiOperation("查询空房")
    @GetMapping("/getentryroom")
    public JSONResult selectEntryRoom() {
        List<Room> rooms = roomService.selectEntryRoom();
//        List bed = new ArrayList();
//        for (Room room:rooms) {
//            bed.add(room.getType()-room.getLivedPeopleNumber());
//        }
//        System.out.println(bed);
        return JSONResult.build(200, "查询成功", roomService.selectEntryRoom());
    }

    /**
     * 管理员根据宿舍号更改退换宿状态
     *
     * @param userChangeRoom
     * @return
     */
    @ApiOperation("管理员根据宿舍号更改退换宿状态")
    @PostMapping("/updateChangeRoomOrderState")
    public JSONResult updateChangeRoomOrderState(UserChangeRoom userChangeRoom) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        User user = new User();
        String date = df.format(new Date());
        //根据用户id查找这条订单的所有信息
        UserChangerRoomVO userChangerRoomVO = roomService.selectUserChangeRoomById(userChangeRoom.getId());
        try {
            //点击同意
            if (userChangeRoom.getState() == 0) {
                //为退宿的情况
                if (userChangerRoomVO.getType().equals((byte) 1)) {
                    //设置用户最终离开的信息
                    user.setId(userChangerRoomVO.getUid());
                    user.setLeaveTime(date);
                    user.setRoomId(null);
                    userService.update(user);
                    //原来住的宿舍减少一个床位
                    roomService.reduceRoomNumber(userChangerRoomVO.getRoomId());
                    //删除用户信息
                    userService.deleteUser(userChangerRoomVO.getUid());
                    //更改退换宿舍状态
                    userChangeRoom.setFinishTime(date);
                    roomService.updateChangeRoomOrderState(userChangeRoom);
                    return JSONResult.build(200, "用户退宿成功，系统已移除用户信息", null);
                } //为换宿情况
                else if (userChangerRoomVO.getType().equals((byte) 2)) {
                    //把要更换到的宿舍增加一个人
                    roomService.addRoomNumber(userChangerRoomVO.getChangeRoomId());
                    //更改个人信息的宿舍号
                    user.setId(userChangerRoomVO.getUid());
                    user.setRoomId(userChangerRoomVO.getChangeRoomId());
                    userService.update(user);
                    userChangeRoom.setFinishTime(date);
                    //原来住的宿舍减少一个床位
                    roomService.reduceRoomNumber(userChangerRoomVO.getRoomId());
                    //加在换宿记录中加一条原宿舍信息
                    userChangeRoom.setOldRoomId(userChangerRoomVO.getRoomId());
                    //更改退换宿舍状态
                    roomService.updateChangeRoomOrderState(userChangeRoom);
                    return JSONResult.build(200, "用户更换宿舍成功", null);
                }
            } else if (userChangeRoom.getState() == 1) {
                //为退宿的情况
                if (userChangerRoomVO.getType().equals((byte) 1)) {
                    //恢复用户信息
                    user.setId(userChangerRoomVO.getUid());
                    user.setLeaveTime(null);
                    user.setRoomId(userChangerRoomVO.getRoomId());
                    user.setDelState((byte) 0);
                    userService.update(user);
                    //原来减掉的床位加回来
                    roomService.addRoomNumber(userChangerRoomVO.getRoomId());
                }
                //为换宿情况
                else if (userChangerRoomVO.getType().equals((byte) 2)) {
                    //个人信息原来的宿舍改回来
                    user.setId(userChangerRoomVO.getUid());
                    user.setRoomId(userChangerRoomVO.getOldRoomId());
                    userService.update(user);
                    //把更换到的宿舍减回原来的数目
                    roomService.reduceRoomNumber(userChangerRoomVO.getChangeRoomId());
                    //原来住的宿舍人数加回来
                    roomService.addRoomNumber(userChangerRoomVO.getOldRoomId());
                    userChangeRoom.setUpdateTime(date);

                }
                //更改退换宿舍处理状态
                userChangeRoom.setFinishTime(null);
                roomService.updateChangeRoomOrderState(userChangeRoom);
                return JSONResult.build(200, "撤销用户申请，返回未同意状态", null);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return JSONResult.build(401, "操作失败", null);
    }
}